package com.itboye.mengwu.app.ui.aizhiwu;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.BasePtr;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.inageview.ItemEntity;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.ui.mymeng.WoDeDongTaiDetail2;
import com.itboye.mengwu.chatemoji.FaceInputView;
import com.itboye.mengwu.chatemoji.FaceInputView.Face;
import com.itboye.mengwu.chatemoji.FaceInputView.OnFaceClickListener;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.TieZiBaoHanReply;
import com.itboye.mengwu.data.model.TieZiBaoHanReplyBaoBaoLe;
import com.itboye.mengwu.data.model.TieZiModel;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.luntan.comment.adapter.CommentAdapter;
import com.itboye.mengwu.luntan.comment.adapter.CommentReplyAdapter;
import com.itboye.mengwu.luntan.comment.bean.Reply;
import com.itboye.sunsun.volley.Spanned2String;
import com.umeng.common.message.Log;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

//import com.itboye.core.imageview.RoundImage;

public class BaoBaoLeFragment extends BaseFragment implements Observer {

    private Button btn_comment, btn_reply;
    private EditText edt_reply;
    int pageNo = 1;
    private CommentAdapter commentAdapter;
    private CommentReplyAdapter commentReplyAdapter;

    private static final int ONE_COMMENT_CODE = -1;

    private ArrayList<Reply> replyList;

    /**
     * Item数据实体集合
     */
    private ArrayList<ItemEntity> itemEntities;
    /**
     * ListView对象
     */
    private ListView listview;
    // private RoundImage image;
    String imageUrl = "http://hiphotos.baidu.com/baidu/pic/item/7d8aebfebf3f9e125c6008d8.jpg";
    private TextView textGuan;
    private ImageView back;
    TieZiPresenter presenter;
    ArrayList<TieZiModel.GetAllList.UserInfo> arrayListUserInfo = new ArrayList<TieZiModel.GetAllList.UserInfo>();
    private LuntanTieZiBean bean;
    ArrayList<TieZiBaoHanReplyBaoBaoLe.GetAList> aLists = new ArrayList<TieZiBaoHanReplyBaoBaoLe.GetAList>();
    private ImageView emoji;
    protected boolean isShowEmotion;
    private LinearLayout faceInputContainer;
    private FaceInputView faceInputView;
    ImageView txt_title;
    String type = "load";
    int currItem;
    String tid;

    PtrFrameLayout ptr;

    @Override
    public int initView() {
        // TODO Auto-generated method stub
        return R.layout.activity_gerenkongjian;
    }

    @Override
    public void onMyActivityCreated() {
        showProgressDialog("数据加载中，请稍后", true);
        txt_title.setVisibility(View.GONE);
        aLists = new ArrayList<TieZiBaoHanReplyBaoBaoLe.GetAList>();
        commentAdapter = new CommentAdapter(getActivity(), aLists, commentReplyAdapter,
                replyToReplyListener, dianZan, guanzhu);
        listview.setAdapter(commentAdapter);
        presenter = new TieZiPresenter(this);
        BasePtr.setPagedPtrStyle(ptr);
        ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageNo++;
                presenter.getBabayLe(
                        SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
                        "4", pageNo + "", "1");
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                presenter.getBabayLe(
                        SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
                        "4", pageNo + "", "1");
            }
        });
        initCommentData();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        presenter.getBabayLe(
                SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
                "4", pageNo + "", "1");
        commentAdapter.notifyDataSetChanged();
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            pageNo = 1;
            presenter.getBabayLe(
                    SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
                    "4", pageNo + "", "1");
        }
    };

    private void initCommentData() {
        presenter.getBabayLe(
                SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
                "4", pageNo + "", "1");
        listview.setOnScrollListener(new OnScrollListener() {

            /**
             * 滚动状态改变时调用
             */
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 不滚动时保存当前滚动到的位置
                if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                    currItem = listview.getFirstVisiblePosition();
                }
            }

            /**s
             * 滚动时调用
             */
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
            }
        });
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(),
                        WoDeDongTaiDetail2.class);
                intent.putExtra("tid", aLists.get(position).getTid());
                startActivity(intent);
            }
        });
    }

    TextView nodata;

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        IntentFilter filter = new IntentFilter("update");
        getActivity().registerReceiver(receiver, filter);
        if (entity != null) {
            if (entity.getEventType() == TieZiPresenter.TieziFenYeSuccess) {
                if (pageNo==1) {
                    aLists.clear();
                }
                aLists.addAll(((TieZiBaoHanReplyBaoBaoLe) entity.getData())
                        .getList());
                if (aLists.size() > 0) {
                    nodata.setVisibility(View.GONE);
                } else {
                    nodata.setVisibility(View.VISIBLE);
                }
                // initCommentData();
                commentAdapter.notifyDataSetChanged();
            } else if (entity.getEventType() == TieZiPresenter.TiezifenyeFail) {
                nodata.setVisibility(View.VISIBLE);
            } else if (entity.getEventType() == TieZiPresenter.DianzanSuccess) {
                ByAlert.alert(entity.getData() + "");
                // presenter.getBabayLe(uid, "4", pageNo + "", "1");
                Iterator<TieZiBaoHanReplyBaoBaoLe.GetAList> iterable = aLists
                        .iterator();
                while (iterable.hasNext()) {
                    TieZiBaoHanReplyBaoBaoLe.GetAList getAList = iterable
                            .next();
                    if (getAList.getTid().equals(tid)) {
                        getAList.setIsLike("1");

                        break;
                    }
                }
                commentAdapter.notifyDataSetChanged();
            } else if (entity.getEventType() == TieZiPresenter.DianzanyeFail) {
                ByAlert.alert(entity.getData() + "");
                // initCommentData();
            } else if (entity.getEventType() == TieZiPresenter.PinglunSuccess) {
                initCommentData();
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.DeleteCommentSuccess) {
                initCommentData();
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.DeleteCommentFail) {
                initCommentData();
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.GuanzhuSuccess) {
                Log.e("hu...", "gz");
                initCommentData();
                commentAdapter.notifyDataSetChanged();
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.GuanzhuFail) {
                initCommentData();
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.DeletePingLunHuiFuSuccess) {
                initCommentData();
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.DeletePingLunHuiFail) {
                initCommentData();
                ByAlert.alert(entity.getData() + "");
            }
            try {
                closeProgressDialog();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        ptr.refreshComplete();
    }

    /**
     * 发表评论的监听
     */
    private OnClickListener addCommentListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (judgeLogin()) {
                onCreateDialog(ONE_COMMENT_CODE, ONE_COMMENT_CODE);
            }
        }
    };

    /**
     * 回复评论的监听（回复楼主）
     */
    private OnClickListener replyToCommentListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (judgeLogin()) {
                int position = (Integer) v.getTag();
                onCreateDialog(ONE_COMMENT_CODE, position);
                // Intent intent = new Intent(getActivity(),
                // WoDeDongTaiDetail2.class);
                // intent.putExtra("tid", aList.getTid());
                // intent.putExtra("title", aList.getSubject());
            }
        }
    };
    protected String isReplyOrComment;

    /**
     * 互相回复的监听（楼中楼）
     */
    private OnClickListener replyToReplyListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (judgeLogin()) {
                int parentPosition = (Integer) v.getTag(R.id.tag_first);
                int childPosition = (Integer) v.getTag(R.id.tag_second);
                String authorId = (String) v.getTag(R.id.tag_third);
                isReplyOrComment = v.getTag(R.id.tag_fourth) + "";
                if (authorId.equals((String) SPUtils.get(getActivity(), null,
                        SpPublicParams.UID, ""))) {

                    oncreateDeleteDialog(parentPosition, childPosition,
                            authorId);
                } else {
                    onCreateDialog(parentPosition, childPosition);
                }
            }
        }
    };

    public OnClickListener guanzhu = new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (judgeLogin()) {
                showProgressDialog("请求提交中,请稍后", true);
                String bUid = (String) v.getTag();
                String isFocus = (String) v.getTag(R.id.tag_first);
                System.out.println(bUid + "isFocus" + isFocus);
                if (isFocus.equals("0")) {
                    presenter.guanzhu(
                            SPUtils.get(getActivity(), null,
                                    SpPublicParams.UID, "") + "", bUid, "1");
                } else {
                    presenter.guanzhu(
                            SPUtils.get(getActivity(), null,
                                    SpPublicParams.UID, "") + "", bUid, "0");
                }
            }
        }
    };

    public boolean judgeLogin() {
        if (SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "" == null
                || (SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "")
                .equals("")) {

            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 点赞监听
     */
    private OnClickListener dianZan = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // ByAlert.alert(v.getTag()+"");
            if (judgeLogin()) {
                String islike = v.getTag(R.id.img2) + "";
                tid = v.getTag(R.id.img3) + "";
                if ("0".equals(islike)) {
                    showProgressDialog("请求提交中，请稍后", true);
                    presenter.dianzan(
                            SPUtils.get(getActivity(), null,
                                    SpPublicParams.UID, "") + "", 1 + "", tid);
                    commentAdapter.notifyDataSetChanged();
                } else {
                    ByAlert.alert("已经点过赞了");

                }

            }
        }
    };

    /**
     * 弹出评论的对话框
     *
     * @param parentPositon 父节点的position
     * @param childPostion  子节点的position
     * @return
     */
    protected Dialog onCreateDialog(final int parentPositon,
                                    final int childPostion) {
        final Dialog customDialog = new Dialog(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View mView = inflater.inflate(R.layout.dialog_comment, null);
        edt_reply = (EditText) mView.findViewById(R.id.edt_comments);
        btn_reply = (Button) mView.findViewById(R.id.btn_send);
        emoji = (ImageView) mView.findViewById(R.id.emoji);
        faceInputContainer = (LinearLayout) mView
                .findViewById(R.id.faceInputContainer);
        faceInputView = new FaceInputView(getActivity());
        faceInputContainer.addView(faceInputView);
        faceInputView.setOnClickListener(new FaceInputListenr());
        emoji.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!isShowEmotion) {
                    faceInputContainer.setVisibility(View.VISIBLE);
                } else {
                    faceInputContainer.setVisibility(View.GONE);
                }
                isShowEmotion = !isShowEmotion;
                // ((InputMethodManager)
                // getActivity().getSystemService(MainApplication.INPUT_METHOD_SERVICE))
                // .hideSoftInputFromWindow(getActivity()
                // .getCurrentFocus().getWindowToken(),
                // InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
        customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        customDialog.setContentView(mView);
        customDialog.show();

        btn_reply.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (childPostion) {
                    case ONE_COMMENT_CODE:
                        if (TextUtils.isEmpty(edt_reply.getText().toString())) {
                            Toast.makeText(getActivity(), "内容不能为空",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            TieZiBaoHanReply.GetAList comment = new TieZiBaoHanReply.GetAList();
                        }
                        break;
                    default:
                        if (TextUtils.isEmpty(edt_reply.getText().toString())) {
                            Toast.makeText(getActivity(), "内容不能为空",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            showProgressDialog("数据提交中，请稍后", true);

                            // System.out.println("aLists.get(parentPositon).getReplyInfo().getList().get(childPostion).getAuthorId()"+aLists.get(parentPositon).getReplyInfo().getList().get(childPostion).getAuthorId()+":::"+uid);
                            if (parentPositon != -1) {
                                presenter.huiFuPingLun(
                                        "4",
                                        aLists.get(parentPositon).getReplyInfo()
                                                .getList().get(childPostion)
                                                .getPid(),
                                        aLists.get(parentPositon).getReplyInfo()
                                                .getList().get(childPostion)
                                                .getTid(),
                                        SPUtils.get(getActivity(), null,
                                                SpPublicParams.UID, "") + "",
                                        Spanned2String.parse(edt_reply.getText()),
                                        aLists.get(parentPositon).getReplyInfo()
                                                .getList().get(childPostion)
                                                .getAuthorId());
                                // presenter.huiFuPingLun("4", "57", "109", "153",
                                // "teey", "183");

                            } else {
                                presenter
                                        .pinglun(
                                                aLists.get(childPostion).getFid(),
                                                aLists.get(childPostion).getTid(),
                                                SPUtils.get(getActivity(), null,
                                                        SpPublicParams.UID, "")
                                                        + "",
                                                Spanned2String.parse(edt_reply
                                                        .getText()), null, aLists
                                                        .get(childPostion)
                                                        .getSubject());
                            }
                            initCommentData();
                            customDialog.dismiss();
                            edt_reply.setText("");
                        }
                        break;
                }
            }
        });
        return customDialog;
    }

    private class FaceInputListenr implements OnFaceClickListener {

        @Override
        public void selectedFace(Face face) {
            int id = face.faceId;
            if (id == R.drawable.ic_face_delete_normal)// 删除按钮
            {
                int index = edt_reply.getSelectionStart();
                if (index == 0)
                    return;
                Editable editable = edt_reply.getText();
                editable.delete(index - 1, index);// 删除最后一个字符或表情
            } else {
                edt_reply.append(Html.fromHtml("<img src='" + id + "'/>",
                        imageGetter, null));// 添加表情
            }
        }

    }

    // 输入表情需要
    ImageGetter imageGetter = new ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };

    protected void oncreateDeleteDialog(final int parentPosition,
                                        final int childPosition, final String authorId) {
        // TODO Auto-generated method stub
        final Dialog customDialog = new Dialog(getActivity(), R.style.dialog);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View mView = inflater.inflate(R.layout.dialog_delete_replyorcomment,
                null);
        TextView delete = (TextView) mView.findViewById(R.id.delete);
        TextView cancel = (TextView) mView.findViewById(R.id.cancel);
        // LayoutParams params=new
        // LayoutParams(getActivity().getWindowManager().getDefaultDisplay().getWidth(),100);
        // mView.setLayoutParams(params);
        customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        customDialog.setContentView(mView);

        customDialog.show();
        delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("pid>>>"
                        + aLists.get(parentPosition).getReplyInfo().getList()
                        .get(childPosition).getPid());
                customDialog.dismiss();
                showProgressDialog("数据删除中，请稍后", true);
                if (isReplyOrComment.equals("0")) {
                    presenter.deletePingLun(authorId, "4",
                            aLists.get(parentPosition).getReplyInfo().getList()
                                    .get(childPosition).getTid(),
                            aLists.get(parentPosition).getReplyInfo().getList()
                                    .get(childPosition).getPid());
                } else {
                    presenter.deleteComment(
                            SPUtils.get(getActivity(), null,
                                    SpPublicParams.UID, "") + "",
                            aLists.get(parentPosition).getReplyInfo().getList()
                                    .get(childPosition).getTid(),
                            aLists.get(parentPosition).getReplyInfo().getList()
                                    .get(childPosition).getPid(),
                            isReplyOrComment);
                }
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                customDialog.dismiss();
            }
        });
    }


}
